#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "aimage.h"
#include "aimage_utils.h"
#include "accumulate.h"
#include "aimage_ppm.h"

int main( int argc, const char *argv[] )
{
	char buffer[ 256 ];
	char base[ 256 ];
	FILE *stack_input;
	//AIMAGE image, alpha;
	ACCUMULATOR image;
	int width, height;

	if ( argc != 2 )
	{
		fprintf(stderr, "%s stack_file.txt\n", argv[0] );
		exit( 1 );
	}

	stack_input = fopen( argv[ 1 ], "rt" );
	if ( stack_input == NULL )
	{
		fprintf( stderr, "%s Unable to open %s\n", argv[0], argv[1] );
	}

	assert ( fgets( buffer, 256, stack_input ) != NULL );
	sscanf( buffer, "%s", base );
	AIMAGE frame;
	AIMAGE_PPM_UTILS::load( frame, base );
	frame.get_dim( width, height );
	image.alloc_image( width, height );

	while ( fgets( buffer, 256, stack_input ) != NULL )
	{
		float score;
		char file_name[ 256 ];
		float ratio;
		float score2;
		float distance;
		float orig_to_frame_angle;
		float orig_to_frame_x;
		float orig_to_frame_y;

		sscanf(buffer, "Score %9f File %s Ratio %g Score %g Distance %9f Angle %g XTrans %g YTrans %g\n",
			&score,
			file_name,
			&ratio,
			&score2,
			&distance,
			&orig_to_frame_angle,
			&orig_to_frame_x,
			&orig_to_frame_y );

		fprintf(stderr, "File %s angle %g x %g y %g\n",
			file_name, orig_to_frame_angle, orig_to_frame_x, orig_to_frame_y );

		float frame_to_orig_angle;
		float frame_to_orig_x;
		float frame_to_orig_y;

		frame_to_orig_angle = -orig_to_frame_angle;	// inverse
		frame_to_orig_x = 
				cosf( frame_to_orig_angle ) * -orig_to_frame_x -
				sinf( frame_to_orig_angle ) * -orig_to_frame_y;
		frame_to_orig_y = 
				sinf( frame_to_orig_angle ) * -orig_to_frame_x +
				cosf( frame_to_orig_angle ) * -orig_to_frame_y;

		ASTAR_TRANSFORM t;
		t.xo = frame_to_orig_x;
		t.yo = frame_to_orig_y;
		t.angle = frame_to_orig_angle;
		//t.xo = orig_to_frame_x;
		//t.yo = orig_to_frame_y;
		//t.angle = orig_to_frame_angle;

		AIMAGE_PPM_UTILS::load( frame, file_name );
		image.rotate_and_add( frame, t ); 	
	}

	fprintf(stderr,"Converting accumulation back to image\n");
	image.to_image( frame );
	fprintf(stderr,"Writing image is stacked_image.ppm\n");
	AIMAGE_PPM_UTILS::save( frame, "stacked_image.ppm", true );
}

